<template>
  <a-card title="查看楼栋信息" style="width: 300px;pointer-events: all;">
    <span style="margin-right: 20px;">楼栋选择:</span>
    <a-select ref="select" v-model:value="selectBuild" style="width: 150px" :options="buildsOption"
      @change="handleChange"></a-select>
    <div v-if="selectedBuilding" style="margin-top: 10px;">
      <div>楼栋名称: {{ selectedBuilding.label }}</div>
      <div>单元数量: {{ units.length }}</div>
      <div>住户数量: {{ totalHouseholds }}</div>
      <div>已入住: {{ occupiedHouseholds }}</div>
      <div>未入住: {{ vacantHouseholds }}</div>
      <div>入住率: {{ occupancyRate }}%</div>
    </div>
  </a-card>
</template>

<script setup>
import * as Cesium from 'cesium'
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { getBuildings, getHouseholdsByUnit, getUnitsByBuilding } from '@/api/api'
import * as turf from '@turf/turf'
import { useMapData } from '@/store'

const selectBuild = ref('') // 存储当前选中的楼栋ID，用于下拉选择框的v-model绑定
const buildsOption = ref([])
const selectedBuilding = ref(null)// 存储当前选中楼栋的完整信息
const units = ref([])
const totalHouseholds = ref(0)
const occupiedHouseholds = ref(0)
const vacantHouseholds = ref(0)
// 计算入住率（百分比）
const occupancyRate = computed(() =>
  totalHouseholds.value === 0 ? 0 : Math.round((occupiedHouseholds.value / totalHouseholds.value) * 100)
)

const mapStore = useMapData()
const viewer = mapStore.Viewer
// 存放所有3D模型对象，便于后续清理
const houseList = []

// 楼栋选择事件处理函数
const handleChange = async (e) => {
  // 清理现有3D模型
  houseList.forEach(item => {
    if (viewer && !viewer.isDestroyed()) {
      viewer.scene.primitives.remove(item)
    }
  })
  houseList.length = 0

  // 重置统计数据和单元列表
  units.value = []
  totalHouseholds.value = 0
  occupiedHouseholds.value = 0
  vacantHouseholds.value = 0
  // 查找选中的楼栋
  const target = buildsOption.value.find(item => item.value === e)
  if (!target) return

  selectedBuilding.value = target
  // 解析楼栋多边形数据（GeoJSON）,确保是对象
  const polygonData = typeof target.polygon === 'string' ? JSON.parse(target.polygon) : target.polygon

  // 计算中心点并飞行定位
  const center = turf.center(polygonData)
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(...center.geometry.coordinates, 250)
  })

  // 获取单元列表
  const unitsRes = await getUnitsByBuilding(e)
  if (unitsRes?.code === 200) {
    units.value = unitsRes.data

    // 遍历每个单元
    for (const unit of unitsRes.data) {
      const householdsRes = await getHouseholdsByUnit(unit.id)
      if (householdsRes?.code !== 200) continue

      // 统计住户信息
      const households = householdsRes.data
      totalHouseholds.value += households.length
      households.forEach(household => {
        if (household.owner_name?.trim()) {
          occupiedHouseholds.value++
        } else {
          vacantHouseholds.value++
        }
      })

      // 渲染3D模型
      const unitPolygon = typeof unit.polygon === 'string' ? JSON.parse(unit.polygon) : unit.polygon
      const coordinates = unitPolygon.coordinates?.[0] || unitPolygon
      const arr = coordinates.flat()

      households.forEach((household, index) => {
        // 为每个住户生成随机颜色
        const randomColor = Cesium.Color.fromRandom({
          alpha: 0.5,  // 设置透明度
          minimumRed: 0.1,  // 最小红色值
          minimumGreen: 0.1,  // 最小绿色值
          minimumBlue: 0.1,  // 最小蓝色值
          maximumRed: 0.9,  // 最大红色值
          maximumGreen: 0.9,  // 最大绿色值
          maximumBlue: 0.9   // 最大蓝色值
        })

        // 创建可以分类的3D图元，可以显示在3D模型上
        const primitive = new Cesium.ClassificationPrimitive({
          // 定义3D图元的具体形状和属性
          geometryInstances: new Cesium.GeometryInstance({
            // 定义多边形的几何形状
            geometry: new Cesium.PolygonGeometry({
              // 定义多边形的顶点和形状
              polygonHierarchy: new Cesium.PolygonHierarchy(
                // 将经纬度数组转换为Cesium的坐标
                Cesium.Cartesian3.fromDegreesArray(arr)
              ),
              height: parseFloat(household.min_height),
              extrudedHeight: parseFloat(household.max_height)
            }),
            attributes: {
              color: Cesium.ColorGeometryInstanceAttribute.fromColor(randomColor)
            }
          }),
          // 指定这个图元要显示在3D模型上
          classificationType: Cesium.ClassificationType.CESIUM_3D_TILE
        })
        // 保存到houseList便于后续清理
        houseList.push(primitive)
        // 添加到地图场景中
        viewer.scene.primitives.add(primitive)
      })
    }
  }
}

// 组件挂载时加载楼栋列表
onMounted(async () => {
  const buildInfo = await getBuildings()
  if (buildInfo?.code === 200) {
    // 格式化为下拉选项
    buildsOption.value = buildInfo.data.map(item => ({
      value: item.id,
      label: item.name,
      polygon: item.polygon
    }))
  }
})
// 组件卸载时清理3D模型
onBeforeUnmount(() => {
  // 遍历所有3D模型，逐个从地图中移除
  houseList.forEach(item => {
    if (viewer && !viewer.isDestroyed()) {
      viewer.scene.primitives.remove(item)
    }
  })
  // 清空模型列表
  houseList.length = 0
})
</script>

<style scoped lang='less'></style>